package cn.javaxc.mvcwork.util.helper;
import java.io.*;
import java.net.InetAddress;
import java.util.*;
import java.net.*;
import java.sql.Timestamp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import cn.javaxc.mvcwork.util.common.FrameLog;
import cn.javaxc.mvcwork.controller.MVCConfig;
import cn.javaxc.mvcwork.util.common.CommonUtil;
import cn.javaxc.mvcwork.controller.GenericValidator;
import cn.javaxc.mvcwork.framework.actions.TActionContext;
import cn.javaxc.model.page.*;
import cn.javaxc.mvcwork.controller.AppUtils;
import cn.javaxc.mvcwork.controller.MVCConstant;
import net.sf.json.*;
import cn.javaxc.model.base.*;
import cn.javaxc.mvcwork.util.common.StringUtils;
import cn.javaxc.mvcwork.controller.web.PagedListInfo;
import cn.javaxc.mvcwork.util.common.MSecurityUtils;
public class RequestHelper 
{ 
	public String getContextPath(ServletContext context){
		return context.getContextPath()+"/";
	}
	public static String getBasePath(HttpServletRequest request) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + path + "/";
		return basePath;
	}
	public static Object getRequestValue(freemarker.ext.beans.HashAdapter model,String para){
		if (model.getTemplateModel() instanceof freemarker.ext.servlet.HttpRequestHashModel){
			return getRequestValue(((freemarker.ext.servlet.HttpRequestHashModel)model.getTemplateModel()).getRequest(),para);
		}
		return null;
	}
	public static Object getRequestValue(HttpServletRequest request,String para){
		if(request==null)return null;
		if ("login_user_id".equals(para)){
			return MSecurityUtils.getUserEntity().getUser().getXcUserId();
		}else if ("pagination".equals(para)){
			return AppUtils.getPagedListInfo(request, MVCConstant.mvc_page_list, false);
		}
		if (MVCConfig.getConfig()!=null&&MVCConfig.getConfig().get("SESSION.PARAS")!=null){
			if (CommonUtil.asList(MVCConfig.getConfig().get("SESSION.PARAS").split("|")).contains(para)){
				return request.getSession().getAttribute(para);
			}
		}
		
		Object value =request.getAttribute(para);
		if(value==null)value=request.getParameter(para);
		if(value==null)value=request.getParameter(para+".default");
		if (value instanceof String){
			value=((String)value).trim();
		}
		return value;
	}

	public static Object getRequestValue(HttpServletRequest request,Map map,String para){
		Object value =null;
		if (map!=null){
			if (!"login_user_id".equals(para)){
				value=map.get(para);
			}
		}
		
		if(value==null){
			value=getRequestValue(request,para);	
		}
		if (value instanceof String){
			value=((String)value).trim();
		}
		return value;
	}
	public static Object getRequestValue(HttpServletRequest request,Map map,String para,Object _def){
		Object value =getRequestValue(request,map,para);
		if (value==null){
			value=_def;
		}
		return value;
	}	
	public static void writeJson(HttpServletResponse response,Object object) throws IOException{
		response.setContentType("application/json; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		String rows="rows";//rows
		if (object instanceof SQLList){
			SQLList slist=(SQLList)object;
			PagedListInfo pagedListInfo=slist.getPagedListInfo();
			if (pagedListInfo!=null){
				Map map = new HashMap();
				map.put("total",pagedListInfo.getMaxRecords() );
				map.put("totalPages",pagedListInfo.getNumberOfPages());
				map.put("pageSize",pagedListInfo.getItemsPerPage());
				int pageNo=(pagedListInfo.getItemsPerPage() != -1 ? ((pagedListInfo.getCurrentOffset() / pagedListInfo.getItemsPerPage()) + 1) : 1);
				map.put("pageNo",pageNo);
				map.put(rows,slist.getMapList());
				object=map;
			}
		}
		JsonConfig config=new JsonConfig();
		config.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		if (object instanceof List){
			List list=(List)object;
			Map map = new HashMap();
			map.put("total",list.size() );
			map.put("totalPages",1);
			map.put("pageSize",list.size());
			map.put("pageNo",1);
			if (object instanceof SQLList){
				map.put(rows,((SQLList)object).getMapList());
			}else{
				map.put(rows,list);
			}
			if(map.get("msg")==null)map.put("msg","操作成功");
			if(map.get("code")==null)map.put("code",200);
			object=map;
			response.getWriter().print(JSONObject.fromObject(object,config));
		}else if (object instanceof String){
			response.getWriter().print(object);
		}else if (object instanceof Map){
			Map map=(Map)object;
			if(map.get("msg")==null)map.put("msg","操作成功");
			if(map.get("code")==null)map.put("code",200);
			response.getWriter().print(JSONObject.fromObject(map,config));
		}else{
			response.getWriter().print(object==null?"null":JSONObject.fromObject(object,config));
		}
	}
	public static String addTParams(HttpServletRequest request, String tmp){
		return URLHelper.addTParams(request,tmp);
	}
	public static String getTParams(HttpServletRequest request){
		return URLHelper.getTParams(request);
	}

	public static boolean verifyCode(HttpServletRequest request,Object object,String field){
		if ("false".equals(MVCConfig.getConfig().getCheckLoginCode()))return true;
		if(field==null)field="validatecode";
		String validatecode=request.getParameter(field);
		Object rand=request.getSession().getAttribute("session_verifycode");
		if(rand==null){
			GenericValidator.addError(null,object,field,"验证码无效");
			return false;
		}
		request.getSession().removeAttribute("session_verifycode");
		if ("compareFalse".equals(MVCConfig.getConfig().getCheckLoginCode()))return true;
		String sesscode = (String)rand;
		if (!sesscode.equalsIgnoreCase(validatecode)){
			GenericValidator.addError(null,object,field,"验证码错误");
			return false;
		}
		return true;
	}
	public void createTParams(HttpServletRequest request){
		request.setAttribute("mvcparams",appendTParams(request));
		SQLList elist=new SQLList();

	}
	public String appendTParams(HttpServletRequest request){
	 StringBuffer sb = new StringBuffer();
	  for (String s:getTParamArray()){
		sb.append(addTParams(request,s));
	  }

		Enumeration<String> e = request.getParameterNames();
	    while (e.hasMoreElements()){
			String param = e.nextElement();
			if (param.startsWith("CMID")){
				if (request.getParameter(param)!=null){
					sb.append("&" + param + "=" +request.getParameter(param));
				}			
			}
		}

		e = request.getAttributeNames();
	    while (e.hasMoreElements()){
			String param = e.nextElement();
			if (param.toString().startsWith("CMID")){
				if (request.getAttribute(param)!=null){
					sb.append("&" + param + "=" +request.getAttribute(param));
				}			
			}
		}
		return sb.toString();
	}
	public List<String> getTParamArray(){
		return (List<String>)MVCConfig.getConfig().getClassCfg(MVCConfig.class).get("CMID.PARAS");
	}
	public TActionContext getActionContext(PageContext context){
		return new TActionContext(null, (HttpServletRequest)context.getRequest(), (HttpServletResponse)context.getResponse());
	}

	public void includePage(PageContext pageContext) throws javax.servlet.ServletException,IOException{
		String includePage = (String) pageContext.getRequest().getAttribute("IncludePage");
		if (includePage.endsWith(".jsp")){
			pageContext.include(includePage);
		}
	}
	public VUEPageFile createFilePage(){
		return new VUEPageFile();
	}
	public static String httpGet(String url)throws Exception{
		return httpGet(URI.create(url));
	}
    public static String httpGet(URI url)throws Exception{
        //get请求返回结果
        String strResult = null;
		DefaultHttpClient client = new DefaultHttpClient();
		//发送get请求
		HttpGet request = new HttpGet(url);
		HttpResponse response = client.execute(request);

		/**请求发送成功，并得到响应**/
		if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
			/**读取服务器返回过来的json字符串数据**/
			strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
		} else {
			FrameLog.error("get请求提交失败:" + url);
		}
        return strResult.trim();
    }
}
